# 线性回归的4种方法
# 方法2：向量方法

import numpy as np
import matplotlib.pyplot as plt



# 方法2，构造多元线性回归，向量形式
def method2(xx, yy):
    m = xx.shape[0]
    ones = np.ones([m, 1])

    X = np.hstack((xx, ones))

    # aa = np.linalg.inv(X.T.dot(X))
    # bb = X.T.dot(yy)
    aa = np.linalg.inv(X.T @ X)
    bb = X.T @ yy
    w = aa.dot(bb)
    return w


def func(x, w, b):
    return x * w + b

# Press the green button in the gutter to run the script.
if __name__ == '__main__':
    # print_hi('PyCharm')

    m = 101
    x_train = np.linspace(-1, 1, m)
    x_train = x_train.reshape(-1, 1)
    print(x_train.shape)
    y_train = 2 * x_train + np.random.randn(*x_train.shape) * 0.33

    ##########################################################方法2
    wbar = method2(x_train, y_train)
    print(wbar, wbar.shape)
    w = wbar[:-1, 0]
    b = wbar[-1, 0]
    # print(w, w.shape, x_train.shape)
    # print(b, b.shape)

    # xx = x_train
    # zzz = x_train * w + b
    xx = np.array([[-1], [1]])#.reshape(-1, 1)
    zzz = xx * w + b

    plt.figure(2)
    plt.scatter(x_train, y_train)
    plt.plot(xx, zzz, color='m', linewidth=4.0, linestyle="--")
    # plt.pause(1)
    plt.show()
